<template>
    <div class="icon-dropdown position-relative" ref="dropdownRef">
        <button
            class="btn btn-outline-secondary dropdown-toggle w-100 text-start d-flex align-items-center justify-content-between"
            :class="{ 'is-invalid': required && !modelValue }"
            @click="toggleDropdown"
            type="button"
            :disabled="disabled || loading"
        >
            <span class="d-flex align-items-center gap-2">
                <!-- 加载中 -->
                <span v-if="loading">
                    <span class="spinner-border spinner-border-sm me-1" role="status" />
                    加载分类....
                </span>

                <!-- 展示选中项或 placeholder -->
                <template v-else>
                    <i v-if="selectedOption" :class="[selectedOption.icon, selectedOption.color]" />
                    {{ selectedOption?.name || placeholder }}
                </template>
            </span>
        </button>

        <!-- 下拉菜单 -->
        <div v-if="open" class="dropdown-menu show w-100 mt-1 shadow-sm p-2">
            <!-- 搜索框 -->
            <input
                v-model="search"
                type="text"
                placeholder="搜索分类..."
                class="form-control form-control-sm mb-2"
                :disabled="loading"
            />

            <!-- 加载中 -->
            <div v-if="loading" class="dropdown-item text-muted d-flex align-items-center gap-2">
                <span class="spinner-border spinner-border-sm me-2" role="status" />
                正在加载分类...
            </div>

            <!-- 没有匹配项 -->
            <div v-else-if="filteredOptions.length === 0" class="dropdown-item text-muted">
                没有匹配的分类
            </div>

            <!-- 匹配项列表 -->
            <ul class="list-unstyled mb-0">
                <li
                    v-for="item in filteredOptions"
                    :key="item.id"
                    class="dropdown-item d-flex align-items-center gap-2"
                    @click="selectItem(item)"
                >
                    <i :class="[item.icon, item.color]" />
                    {{ item.name }}
                </li>
            </ul>
        </div>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onClickOutside } from '@vueuse/core';

const props = defineProps({
    modelValue: [String, Number],
    options: {
        type: Array,
        required: true
    },
    placeholder: {
        type: String,
        default: '请选择分类'
    },
    required: Boolean,
    disabled: Boolean,
    loading: Boolean
});

const emit = defineEmits(['update:modelValue']);

const open = ref(false);
const dropdownRef = ref(null);
const search = ref('');

// 关闭下拉逻辑
onClickOutside(dropdownRef, () => {
    open.value = false;
});

function toggleDropdown() {
    if (!props.disabled && !props.loading) {
        open.value = !open.value;
        search.value = ''; // 每次打开清空搜索
    }
}

function selectItem(item) {
    emit('update:modelValue', item.id);
    open.value = false;
}

const selectedOption = computed(() => props.options.find(item => item.id === props.modelValue));

// 搜索过滤逻辑（名称字段匹配）
const filteredOptions = computed(() => {
    const keyword = search.value.trim().toLowerCase();
    if (!keyword) return props.options;
    return props.options.filter(item => item.name?.toLowerCase().includes(keyword));
});
</script>

<style scoped>
.icon-dropdown {
    position: relative;
}

.dropdown-menu {
    max-height: 320px;
    overflow-y: auto;
    z-index: 1000;
}

.dropdown-item {
    cursor: pointer;
    user-select: none;
}
</style>
